package com.hsnn.medstgmini.pro.project.dao.impl;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.std.model.StdCompinfo;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.exception.MSException;
import com.hsnn.medstgmini.model.Status;
import com.hsnn.medstgmini.pro.project.dao.PsProjectDao;
import com.hsnn.medstgmini.pro.project.model.form.ProdProjectForm;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.MapToBeanUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 配送企业端项目管理
 * @author wangbing
 * @date 2015年8月24日
 */
@Repository
public class PsProjectDaoImpl implements PsProjectDao {

	@Resource(name = "sessionFactory")
	private SessionFactory factory;

	@Autowired
	private HibernateSqlUtil sqlUtil;

	/**
	 * @category 分页查询项目列表
	 * @date 2015年8月24日
	 * @param page
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	public Pagination getProjectList(Pagination page, SysUser user) {
		StdCompinfo compInfo = user.getInfo();
		String compId = "";
		if (compInfo != null) {
			compId = compInfo.getCompId();
		}
		StringBuffer sb = new StringBuffer();
		sb.append(" select a.proj_id as projId, a.proj_code as projCode, a.name, a.proj_cat as projCat, a.status, DATE_FORMAT(a.create_datetime, '%Y-%m-%d %T') as createDatetime, DATE_FORMAT(a.starttime, '%Y-%m-%d') as starttime, DATE_FORMAT(a.endtime, '%Y-%m-%d') as endtime, a.proj_intro as projIntro, a.remark, CASE WHEN b.comp_id IS NULL THEN 0 ELSE 1 END enroll  from view_bidproject a LEFT JOIN bid_projcompany b ON a.proj_id = b.proj_id AND b.comp_id = :compId where 1=1 AND a.proj_cat = 1 AND a.status = 1  ");
		ProdProjectForm form = (ProdProjectForm) page.getForm();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("compId", compId);
		if (form != null) {
			String projId = form.getProjId();
			if (StringUtils.isNotBlank(projId)) {
				sb.append(" AND a.proj_id = :projId ");
				params.put("projId", projId);
			}
		}
		sb.append(" order by a.starttime desc,a.name ");
		List<Map<String, Object>> list = (List<Map<String, Object>>) sqlUtil.getSqlMapList(sb.toString(), params);
		List<ProdProjectForm> projList = MapToBeanUtil.mapToBean(list,ProdProjectForm.class);
		page.setRows(projList);
		return page;
	}

	/**
	 * @category 分页查询已报名的有效项目
	 * @date 2015年8月24日
	 * @param page
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	public Pagination getMyProjectList(Pagination page, SysUser user) {

		StdCompinfo compInfo = user.getInfo();

		if (compInfo == null) {
			return page;
		}

		String compId = compInfo.getCompId();

		StringBuffer sb = new StringBuffer();
		sb.append(" select a.proj_id as projId, a.proj_code as projCode, a.name, a.proj_cat as projCat, a.status, DATE_FORMAT(a.create_datetime, '%Y-%m-%d %T') as createDatetime, DATE_FORMAT(a.starttime, '%Y-%m-%d') as starttime, DATE_FORMAT(a.endtime, '%Y-%m-%d') as endtime, a.proj_intro as projIntro, a.remark from view_bidproject a JOIN bid_projprodcompany b ON a.proj_id = b.proj_id where 1=1 AND a.proj_cat = 1 AND a.status = 1 AND a.starttime <= SYSDATE() AND A.endtime >= SYSDATE() AND b.prod_comp_id = :compId ");

		ProdProjectForm form = (ProdProjectForm) page.getForm();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("compId", compId);

		if (form != null) {
			String projCode = form.getProjCode();
			if (StringUtils.isNotBlank(projCode)) {
				sb.append(" AND a.proj_code = :projCode ");
				params.put("projCode", projCode);
			}
			String name = form.getName();
			if (StringUtils.isNotBlank(name)) {
				sb.append(" AND a.name LIKE :name ");
				params.put("name", "%" + name + "%");
			}
		}

		sb.append(" order by a.create_datetime desc ");

		sqlUtil.getSqlPageMapList(sb.toString(), params, page);

		List<Map<String, Object>> list = (List<Map<String, Object>>) page
				.getRows();

		List<ProdProjectForm> projList = MapToBeanUtil.mapToBean(list,
				ProdProjectForm.class);

		page.setRows(projList);

		return page;
	}

	/**
	 * @category 企业投标报名
	 * @date 2015年8月24日
	 * @param user
	 */
	public void enroll(String projId, SysUser user) {
		Session session = factory.getCurrentSession();
		StdCompinfo info = user.getInfo();
		if (info != null) {
			String compId = info.getCompId();
			String sql = " SELECT COUNT(*) FROM bid_projcompany WHERE proj_id = :projId AND comp_id = :compId ";
			SQLQuery query = session.createSQLQuery(sql);
			query.setString("projId", projId);
			query.setString("compId", compId);
			Long count = ((BigInteger) query.uniqueResult()).longValue();
			if (count > 0) {
				throw new MSException("已报名，请勿重复报名！");
			}
			sql = " insert into bid_projcompany values (uuid(), :projId , :compId, null, :status, sysdate(), :updUser) ";
			query = session.createSQLQuery(sql);
			query.setString("projId", projId);
			query.setString("compId", compId);
			query.setInteger("status", Status.enabled.getKey());
			query.setString("updUser", user.getId());
			query.executeUpdate();
			session.flush();

			writeEnrollLog(projId);
		}
	}

	/**
	 * @category 记录业投标报名日志
	 * @date 2015年8月24日
	 */
	public void writeEnrollLog(String projId) {
		Session session = factory.getCurrentSession();
		String sql = " insert into bid_projcompany_log select uuid() log_id, a.* from bid_projcompany a where a.proj_id = :projId ";
		SQLQuery query = session.createSQLQuery(sql);
		query.setString("projId", projId);
		query.executeUpdate();
		session.flush();
	}

	/**
	 * @category 项目时间段查看
	 * @date 2015年8月24日
	 * @param projId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	public ProdProjectForm getProjectTimeView(String projId) {
		Session session = factory.getCurrentSession();
		String sql = " SELECT proj_id, DATE_FORMAT(proj_starttime, '%Y-%m-%d %T') projStarttime, DATE_FORMAT(proj_endtime, '%Y-%m-%d %T') projEndtime, DATE_FORMAT(pro_audit_starttime, '%Y-%m-%d %T') proAuditStarttime, DATE_FORMAT(pro_audit_endtime, '%Y-%m-%d %T') proAuditEndtime, DATE_FORMAT(pro_audit_pub_starttime, '%Y-%m-%d %T') proAuditPubStarttime, DATE_FORMAT(pro_audit_pub_endtime, '%Y-%m-%d %T') proAuditPubEndtime, DATE_FORMAT(price_quote_simu_starttime, '%Y-%m-%d %T') priceQuoteSimuStarttime, DATE_FORMAT(price_quote_simu_endtime, '%Y-%m-%d %T') priceQuoteSimuEndtime, DATE_FORMAT(price_quote_starttime, '%Y-%m-%d %T') priceQuoteStarttime, DATE_FORMAT(price_quote_endtime, '%Y-%m-%d %T') priceQuoteEndtime, DATE_FORMAT(price_quote_decode_starttime, '%Y-%m-%d %T') priceQuoteDecodeStarttime, DATE_FORMAT(price_quote_decode_endtime, '%Y-%m-%d %T') priceQuoteDecodeEndtime, DATE_FORMAT(price_grade_starttime, '%Y-%m-%d %T') priceGradeStarttime, DATE_FORMAT(price_grade_endtime, '%Y-%m-%d %T') priceGradeEndtime, DATE_FORMAT(semi_win_pub_starttime, '%Y-%m-%d %T') semiWinPubStarttime, DATE_FORMAT(semi_win_pub_endtime, '%Y-%m-%d %T') semiWinPubEndtime, DATE_FORMAT(appeal_starttime, '%Y-%m-%d %T') appealStarttime, DATE_FORMAT(appeal_endtime, '%Y-%m-%d %T') appealEndtime, DATE_FORMAT(win_pub_starttime, '%Y-%m-%d %T') winPubStarttime, DATE_FORMAT(win_pub_endtime, '%Y-%m-%d %T') winPubEndtime FROM bid_project_details WHERE proj_id = :projId ";
		SQLQuery query = session.createSQLQuery(sql);
		query.setString("projId", projId);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		Map<String, Object> map = (Map<String, Object>) query.uniqueResult();
		ProdProjectForm form = MapToBeanUtil.mapToBean(map,
				ProdProjectForm.class);
		return form;
	}

	/**
	 * @category 设置密码
	 * @date 2015年8月24日
	 * @param projId
	 * @param user
	 */
	public void setPassword(ProdProjectForm form, SysUser user) {
		Session session = factory.getCurrentSession();
		StdCompinfo info = user.getInfo();
		if (info != null) {
			String projId = form.getProjId();
			String compId = info.getCompId();
			String sql = " update bid_projprodcompany set price_key = :priceKey, upd_user = :updUser, upd_datetime = sysdate() where proj_id = :projId and prod_comp_id = :compId ";
			SQLQuery query = session.createSQLQuery(sql);
			query.setString("priceKey", form.getPassword());
			query.setString("updUser", user.getId());
			query.setString("projId", projId);
			query.setString("compId", compId);
			query.executeUpdate();
			session.flush();

			writeEnrollLog(projId);
		}
	}

}
